package bosc.cn.controller;

import bosc.cn.api.LoanApi;
import bosc.cn.converter.loan.LoanApprovalReqConverter;
import bosc.cn.converter.loan.LoanApprovalResConverter;
import bosc.cn.dto.common.CommonResponse;
import bosc.cn.dto.common.RequestWrapper;
import bosc.cn.dto.common.ResponseWrapper;
import bosc.cn.dto.loan.LoanApprovalReqDTO;
import bosc.cn.dto.loan.LoanApprovalResDTO;
import bosc.cn.service.loan.LoanApprovalService;
import bosc.cn.service.loan.bo.LoanApprovalReqBO;
import bosc.cn.service.loan.bo.LoanApprovalResBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/loan")

public class LoanController implements LoanApi {

    @Autowired
    private LoanApprovalService loanApprovalService;

    @PostMapping("/apply")
    public ResponseWrapper<LoanApprovalResDTO> approveLoan(
        @RequestBody RequestWrapper<LoanApprovalReqDTO> reqWrapper) {
        // 获取 body
        LoanApprovalReqDTO body = reqWrapper.getBody();

        // DTO -> BO
        LoanApprovalReqBO reqBO = LoanApprovalReqConverter.toBO(body);

        // 调用 Service，返回 ResponseWrapper<LoanApprovalResBO>
        ResponseWrapper<LoanApprovalResBO> resWrapper = loanApprovalService.approveLoan(reqBO);

        // 从 Service 返回结果中取出 head 和 body
        CommonResponse head = resWrapper.getHead();
        LoanApprovalResBO resBO = resWrapper.getBody();

        // BO -> DTO
        LoanApprovalResDTO resDTO = LoanApprovalResConverter.toDTO(resBO);

        // 封装最终响应（head 原样传递，body 转换成 DTO）
        ResponseWrapper<LoanApprovalResDTO> responseWrapper = new ResponseWrapper<>();
        responseWrapper.setHead(head);
        responseWrapper.setBody(resDTO);

        return responseWrapper;
    }
}
